<?php


namespace App\Form\Type;


use App\Entity\Parameters;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ParamsFieldType extends AbstractType
{
    private $em;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->em = $entityManager;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions($resolver); // TODO: Change the autogenerated stub

        // 设置允许的参数
        $resolver->setDefaults([
            'paths_id' => null
        ]);

        // 参数对应允许的类型
        $resolver->setAllowedTypes('paths_id', ['null', 'int']);
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options); // TODO: Change the autogenerated stub
    }

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        parent::buildView($view, $form, $options); // TODO: Change the autogenerated stub

        $params = [];
        foreach (Parameters::$categories as $in) {
            $params[$in] = [];
        }

        $view->vars['params'] = &$params;
        $view->vars['formats'] = Parameters::$formats;
        $view->vars['categories'] = Parameters::$categories;

        if (!is_null($options['paths_id'])) {
            $paths_id = $options['paths_id'];
            $parameters = $this->em->getRepository(Parameters::class)->findBy(['pathsId' => $paths_id, 'status' => 1]);
            if (count($parameters) > 0) {
                foreach ($parameters as $obj) {
                    $item = [
                        'key' => $obj->getName(),
                        'description' => $obj->getDescription(),
                        'format' => $obj->getFormat(),
                        'required' => $obj->getRequired(),
                    ];
                    if (isset(Parameters::$categories[$obj->getCategory()])) {
                        array_push($params[Parameters::$categories[$obj->getCategory()]], $item);
                    }
                }
            }
        }
    }
}